import { onMounted, onUnmounted, ref } from 'vue'
import { throttle } from 'underscore'

export default function useScroll(elRef) {
  let el = window
  //默认没有滚动到底部
  const isScrollBottom = ref(false)
  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)

  const scrollListenerHandler = throttle(() => {
    if (el === window) {
      console.log('scrollTop.value', scrollTop.value)
      //获取客户端滚动以后视图高度
      clientHeight.value = document.documentElement.clientHeight
      //获取顶部到滚动的高度
      scrollTop.value = document.documentElement.scrollTop
      //获取客户端高度
      scrollHeight.value = document.documentElement.scrollHeight
    } else {
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
    }

    if (clientHeight.value + scrollTop.value >= scrollHeight.value - 1) {
      //滚动到底部了
      isScrollBottom.value = true
    }
  }, 100)

  //挂载完成监听
  onMounted(() => {
    if (elRef) el = elRef.value
    el.addEventListener('scroll', scrollListenerHandler)
  })

  //销毁移除监听
  onUnmounted(() => {
    el.removeEventListener('scroll', scrollListenerHandler)
  })

  return {
    isScrollBottom,
    clientHeight,
    scrollTop,
    scrollHeight
  }
}
